<?php
declare (strict_types=1);

namespace app\system\validate;

use think\Validate;

class UserValidate extends Validate
{
    // 定义正则表达式

    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    // 定义验证规则
    protected $rule = [
        'nickname' => 'require|max:50',
        'username' => 'require|alphaNum|unique:user',
        'password' => 'require|checkPassword',
        'phone' => 'require|mobile|unique:user',
        'email' => 'require|email|unique:user',
        'gender' => 'require|in:0,1,2',
        'status' => 'require|in:0,1',
        'remark' => 'max:255',
    ];

    // 定义错误消息
    protected $message = [
        'nickname.require' => '昵称必须填写',
        'nickname.max' => '昵称最多不能超过50个字符',

        'username.require' => '用户名必须填写',
        'username.alphaNum' => '用户名只能是字母和数字',
        'username.unique' => '用户名已存在',

        'password.require' => '密码必须填写',
        'password.checkPassword' => '密码格式不正确，应为8-18位数字、字母、符号的任意两种组合',

        'phone.require' => '手机号必须填写',
        'phone.mobile' => '手机号格式不正确',
        'phone.unique' => '手机号已被注册',

        'email.require' => '邮箱地址必须填写',
        'email.email' => '邮箱格式不正确',
        'email.unique' => '邮箱已被注册',

        'gender.require' => '性别必须选择',
        'gender.in' => '性别选择不正确',

        'status.require' => '状态必须指定',
        'status.in' => '状态值不正确',

        'remark.max' => '备注最多不能超过255个字符',
    ];



    // 自定义验证规则
    protected function checkPassword($value)
    {
        $patterns = [
            '/^(?=\S{8,18}$)(?=\S*[A-Za-z])(?=\S*[\d])[\w\W]*$/', // 字母和数字
            '/^(?=\S{8,18}$)(?=\S*[A-Za-z])(?=\S*[\W])[\w\W]*$/', // 字母和特殊字符
            '/^(?=\S{8,18}$)(?=\S*[\d])(?=\S*[\W])[\w\W]*$/',    // 数字和特殊字符
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $value)) {
                return true;
            }
        }

        return false;
    }
    // 可以定义验证场景
    protected $scene = [
        'status' => [ 'status'],
        'resetPassword' => [ 'password'],
        'edit'    => ['username', 'nickname', 'phone', 'email', 'gender', 'status', 'remark'],
    ];

}
